package com.pipe.servicepipe.handler;

import cn.hutool.json.JSONUtil;
import com.pipe.servicepipe.annotation.OperationAnnotation;
import com.pipe.servicepipe.entity.PipeLog;
import com.pipe.servicepipe.service.PipeLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @ClassName LogAop
 * @Author HETAO
 * @Date 2020/7/12 11:12
 */
@Aspect
@Component
@Order(1)
@Slf4j
public class WebLogAspect {
    @Resource
    private PipeLogService pipeLogService;

    @Pointcut("execution(public * com.pipe.servicepipe.controller..*.*(..))")//切入点描述
    public void LogAspect() {
    }

    @Around("LogAspect()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object proceed = proceedingJoinPoint.proceed();
        long end = System.currentTimeMillis() - start;
        ServletRequestAttributes requestAttributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        PipeLog pipeLog = new PipeLog();
        //获取操作员
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        Class clazz = proceedingJoinPoint.getTarget().getClass();

        MethodSignature ms =(MethodSignature) proceedingJoinPoint.getSignature();
        Method m = clazz.getDeclaredMethod(ms.getName(),ms.getParameterTypes());
        OperationAnnotation annotation = m.getAnnotation(OperationAnnotation.class);
        pipeLog.setOperation("无详细描述");
        if (annotation != null) {
            //操作描述
            String value = annotation.value();
            pipeLog.setOperation(value);
        }
        pipeLog.setUri(request.getRequestURI());
        pipeLog.setOperator(name);
        pipeLog.setSpendTime(end);
        pipeLog.setIp(request.getRemoteAddr());
         pipeLog.setMethod(request.getMethod());
        pipeLogService.save(pipeLog);
        log.info("{}", JSONUtil.parse(pipeLog).toString());
        return proceed;
    }

    /**
     * 根据方法和传入的参数获取请求参数
     */
    private Object getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (!StringUtils.isEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        if (argList.size() == 0) {
            return null;
        } else if (argList.size() == 1) {
            return argList.get(0);
        } else {
            return argList;
        }
    }
}
